//
//  KFWAlertView.m
//  测试2
//
//  Created by 孔六五 on 14/11/19.
//
//

#import "KFWAlertView.h"


static UIColor *kfwBackGroundColor;
static UIColor *kfwTopGroundColor;

static UIFont *kfwTitleFont;
static UIFont *kfwFont;
static const CGFloat kfwRingRadius = 7;
static const CGFloat kfwImageLengthOfSide = 80.0;
static const CGFloat kfwSpace = 10.0;

@interface KFWAlertView()
@property (nonatomic,strong) UIButton *cancelBtn;
@property (nonatomic,strong) UILabel *titleLab;
@property (nonatomic,strong) UIImageView *titleImageView;
@property (nonatomic,strong) UILabel *messageLab;
@property (nonatomic,strong) NSString *titleStr;
@property (nonatomic,strong) NSString *messageStr;
@property (nonatomic,strong) NSString *cancelBtnTitle;
@property (nonatomic,strong) UIImage *titleImage;

@end
@implementation KFWAlertView

+ (KFWAlertView*)sharedView {
    static dispatch_once_t once;
    static KFWAlertView *sharedView;
    //    dispatch_once(&once, ^ { sharedView = [[self alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; });
    dispatch_once(&once, ^ {
        CGRect frame = [UIScreen mainScreen].bounds;
//        CGFloat l = MAX(((NSInteger)frame.size.width), ((NSInteger)frame.size.height));
//        sharedView = [[self alloc] initWithFrame:CGRectMake(0, 0, l, l)];
        sharedView = [[self alloc] initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
    });
    return sharedView;
}

- (id)initWithFrame:(CGRect)frame {
    
    if ((self = [super initWithFrame:frame])) {
        self.userInteractionEnabled = YES;
        kfwBackGroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        kfwTopGroundColor = [UIColor colorWithRed:222/255.0 green:224/255.0 blue:224/255.0 alpha:1.0];
        kfwTitleFont = [UIFont systemFontOfSize:16];
        kfwFont = [UIFont systemFontOfSize:13];

        self.backgroundColor = kfwBackGroundColor;
        self.alpha = 0;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
    }
    return self;
}

+ (void)showKFWAlertView
{
    
}

+ (void)showKFWAlertViewWithTitle:(NSString *)atitle titleImage:(UIImage *)img andMessage:(NSString *)amessage cancelbtn:(NSString *)cancelBtnTitle
{
    [[self sharedView] initializeDataWith:atitle andTitleImage:img andMessage:amessage andCancelBtnTitle:cancelBtnTitle];
}

+ (void)dismissKFWAlertView
{
    
}

- (void)initializeDataWith:(NSString *)titleStr andTitleImage:(UIImage *)img andMessage:(NSString *)amessage andCancelBtnTitle:(NSString *)cancelTitle
{
    self.titleStr = titleStr;
    self.messageStr = amessage;
    self.titleImage = img;
    self.cancelBtnTitle = cancelTitle;
    [self updateFrameSubViews];
    [self addViewToWindow];
}


- (void)updateFrameSubViews
{
    float height = 0;
    
    if (!self.topView) {
        self.topView = [[UIView alloc] init];
        self.topView.backgroundColor = kfwTopGroundColor;
        self.topView.layer.cornerRadius = kfwRingRadius;
        self.topView.frame = CGRectMake(0, 0, 260, 0);
        [self addSubview:self.topView];
    }
    
    if (self.titleStr != nil)
    {
        if (!self.titleLab)
        {
            self.titleLab = [[UILabel alloc] init];
            self.titleLab.backgroundColor = [UIColor clearColor];
            self.titleLab.font = kfwTitleFont;
            self.titleLab.textAlignment = NSTextAlignmentCenter;
            self.titleLab.textColor = [UIColor blackColor];
            self.titleLab.numberOfLines = 0;
        }
        self.titleLab.text = self.titleStr;
        float titleLabheight = [self heightForLab:self.titleStr withFont:self.titleLab.font labWidth:self.topView.frame.size.width - kfwSpace * 2];
        self.titleLab.frame = CGRectMake(kfwSpace, 3, self.topView.frame.size.width - kfwSpace * 2, titleLabheight);
        
        height = height + titleLabheight + 3;
        [self.topView addSubview:self.titleLab];
    }
    else
    {
        if (self.titleLab) {
            self.titleLab.text = nil;
            self.titleLab.frame = CGRectMake(0, 0, 0, 0);
        }
    }
    
    if (self.titleImage != nil) {
        if (!self.titleImageView) {
            self.titleImageView = [[UIImageView alloc] init];
        }
        
        if (self.titleImage.size.width >= self.titleImage.size.height) {
            float multiple = kfwImageLengthOfSide/self.titleImage.size.width;
            float imageviewheight = self.titleImage.size.height * multiple;
            
            self.titleImageView.frame = CGRectMake((self.topView.frame.size.width - kfwImageLengthOfSide)/2, height + kfwSpace, kfwImageLengthOfSide, imageviewheight);
            height = height + imageviewheight + kfwSpace;
        }
        else
        {
            float multiple = kfwImageLengthOfSide/self.titleImage.size.height;
            float imageviewwidth = self.titleImage.size.width * multiple;
            self.titleImageView.frame = CGRectMake((self.topView.frame.size.width - imageviewwidth)/2, height + kfwSpace, imageviewwidth, kfwImageLengthOfSide);
            
            height = height + kfwImageLengthOfSide + kfwSpace;
        }
        
        if (self.titleLab.frame.size.height == 0) {
            self.titleImageView.frame = CGRectMake(self.titleImageView.frame.origin.x, self.titleImageView.frame.origin.y + kfwSpace, self.titleImageView.frame.size.width, self.titleImageView.frame.size.height);
            height = height + kfwSpace;

        }
        
        self.titleImageView.image = self.titleImage;
        [self.topView addSubview:self.titleImageView];
        
    }
    else
    {
        if (self.titleImageView) {
            self.titleImageView.image = nil;
            self.titleImageView.frame = CGRectMake(0, 0, 0, 0);
        }
    }
    
    
    if (self.messageStr != nil) {
        if (!self.messageLab) {
            self.messageLab = [[UILabel alloc] init];
            self.messageLab.backgroundColor = [UIColor clearColor];
            self.messageLab.font = kfwFont;
            self.messageLab.textAlignment = NSTextAlignmentCenter;
            self.messageLab.textColor = [UIColor blackColor];
            self.messageLab.numberOfLines = 0;
        }
        
        self.messageLab.text = self.messageStr;
        float messageLabheight = [self heightForLab:self.messageStr withFont:self.messageLab.font labWidth:self.topView.frame.size.width - kfwSpace*2];
        self.messageLab.frame = CGRectMake(kfwSpace, height + kfwSpace, self.topView.frame.size.width - kfwSpace*2, messageLabheight);
        
        height = height + messageLabheight + kfwSpace;
        [self.topView addSubview:self.messageLab];
    }
    else
    {
        if (self.messageLab) {
            self.messageLab.text = nil;
            self.messageLab.frame = CGRectMake(0, 0, 0, 0);
        }
    }
    
    
    if (self.cancelBtnTitle != nil) {
        if (!self.cancelBtn) {
            self.cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom
                                    ];
            self.cancelBtn.backgroundColor = [UIColor clearColor];
            [self.cancelBtn setTitle:self.cancelBtnTitle forState:UIControlStateNormal];
            [self.cancelBtn setTitleColor:[UIColor colorWithRed:29/255.0 green:105/255.0 blue:248/255.0 alpha:1.0] forState:UIControlStateNormal];
            [self.cancelBtn addTarget:self action:@selector(hidenTheKFWAlertView) forControlEvents:UIControlEventTouchUpInside];
        }
        
        UIView *lineview = (UIView *)[self.topView viewWithTag:100];
        if (!lineview) {
            lineview = [[UIView alloc] init];
            lineview.backgroundColor = [UIColor colorWithRed:178/255.0 green:182/255.0 blue:182/255.0 alpha:1.0];
            lineview.tag = 100;
        }
        lineview.frame = CGRectMake(0, height + kfwSpace, self.topView.frame.size.width, 1);
        [self.topView addSubview:lineview];
        
        self.cancelBtn.frame = CGRectMake(0, height + kfwSpace + 1, self.topView.frame.size.width, 44);
        [self.topView addSubview:self.cancelBtn];
        height = height + 44 + kfwSpace + 1;


    }
    else
    {
        if (self.cancelBtn) {
            self.cancelBtn.frame = CGRectMake(0, 0, 0, 0);
        }
    }
    
    self.topView.frame = CGRectMake((self.frame.size.width - self.topView.frame.size.width)/2, (self.frame.size.height - height)/2, self.topView.frame.size.width, height);
}

- (void)addViewToWindow
{
    NSEnumerator *frontToBackWindows = [[[UIApplication sharedApplication]windows]reverseObjectEnumerator];
    
    for (UIWindow *window in frontToBackWindows)
        if (window.windowLevel == UIWindowLevelNormal) {
            [window addSubview:self];
            break;
        }
    
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.alpha = 1.0;
                     }
                     completion:^(BOOL finished){
                     }];

}

- (void)hidenTheKFWAlertView
{
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         self.alpha = 0;
                     }
                     completion:^(BOOL finished){
                     }];

}

- (float)heightForLab:(NSString *)str withFont:(UIFont *)font labWidth:(float)width
{
    CGSize asize = CGSizeMake(width,2000);
    CGSize labelsize = CGSizeMake(0, 0);
    if (IOS6_VERSION) {
        labelsize = [str sizeWithFont:font constrainedToSize:asize lineBreakMode:NSLineBreakByWordWrapping];
    }
    else
    {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
        labelsize = [str boundingRectWithSize:asize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    }
    
    return labelsize.height + 20;
}


@end
